package fr.alesia.deepstack.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import fr.alesia.deepstack.bean.Player;
import fr.alesia.deepstack.bean.Ranking;
import fr.alesia.deepstack.bean.Tournament;
import fr.alesia.deepstack.factory.IOFactory;
import fr.alesia.deepstack.io.BeanLoader;

@SuppressWarnings("serial")
public class ImportServlet extends HttpServlet {
	
	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		
		if(isMultipart){
			try {
				
				List<FileItem> items = upload.parseRequest(request);
				for (FileItem item : items) {
					
					if(!item.isFormField()){
						
						InputStream stream = item.getInputStream();
						String fieldName = item.getFieldName();
						
						try {
							if("players".equals(fieldName)){
								BeanLoader<Player> loader = IOFactory.getPlayerLoader();
								loader.load(stream);
							}
							if("tournaments".equals(fieldName)){
								BeanLoader<Tournament> loader = IOFactory.getTournamentLoader();
								loader.load(stream);
							}
							if("rankings".equals(fieldName)){
								BeanLoader<Ranking> loader = IOFactory.getRankingLoader();
								loader.load(stream);
							}
							if("database".equals(fieldName)){
								
							}
						}
						catch (Exception e) {
							Logger.getLogger("deepstack").severe(e.getMessage());
							e.printStackTrace();
						}
						stream.close();
						stream = null;
					}
				}
			}
			catch (FileUploadException e) {
				
				Logger.getLogger("deepstack").severe(e.getMessage());
				e.printStackTrace();
			}
		}
		ServletContext context = this.getServletContext();
		RequestDispatcher dispatcher = context.getRequestDispatcher("/webapp/page/admin/import.jsp");
		dispatcher.forward(request, response);
	}

	@Override
	protected void doPost (
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		
		this.doGet(request, response);
	}
}
